/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cassandrawindow;

import count.FraudCountByGuid;
import count.FraudGuidInSecRangeResult;
import countbannerdomain.FraudBannerTimestampDomain;
import countbannerdomain.FraudCountDomainPerBannerInTimestamp;
import countdate.FraudCountByGuidInDate;
import countdate.FraudGuidInDateRangeResult;
import countdatebanner.FraudCountGuidBannerInDate;
import java.io.IOException;
import java.lang.String;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.apache.log4j.xml.DOMConfigurator;
import util.ConfigUtil;

public class HandleFraudClickByDomain {
    public static final String KEYSPACE                             =   "AdsData";
    public static final String ColumFamly                           =   "BannerViewCountCf";
    public static final String ColumFamlyBannerClickCountCf         =   "BannerClickCountCf";
    public static final String ColumFamlyBannerViewCountCf          =   "BannerViewCountCf";

    public static final String ColumFamlyCampaignClickCountCf           =   "CampaignCountCf";
    public static final String ColumFamlyCampaignViewCountCf            =   "CampaignViewCountCf";

    public static final String ColumFamlyCampaignIPCountCf              =   "CampaignIpCountCf";
    public static final String SuperColumFamlyCampaignGuidClick         =   "Guid_Click_Super_Cf";
    public static final String ColumFamlyGuidDataContentBanneridData    =   "GuidDate_Content_Bannerid_DataCF";

    public static final String ColumFamlyBannerTimestampDomain          =   "BannerTimestampDomain_Content_blank_DataCF";

    public static final String FRAUDCLICKKEYSPACE                       =   "FraudKs";

    public static long checkFraudClickbyDomain   =   0;
    
    public void handleData() throws ParseException, InterruptedException, IOException
    {
        int count = 0;
        long first_time = System.currentTimeMillis();
        List<String> domainList = new ArrayList<String>();
        String[] arrDomain = new String[100];        
        try{
            CassandraAction cassAct = new CassandraAction(ACCOUNT.CLUSTERNAME ,ACCOUNT.URL, ACCOUNT.PORT);
            cassAct.initReadWirte(FRAUDCLICKKEYSPACE);
            //ConfigUtil.setPathConfig("E:\\config_fraud_click\\conf.properties");
            //DOMConfigurator.configure("E:\\config_fraud_click\\log4j.xml");
            
            ConfigUtil.setPathConfig("/home/bigdata/cpc/properties/conf.properties");
            DOMConfigurator.configure("/home/bigdata/cpc/properties/log4j.xml");
            
            MysqlDataManagerMain mysqlmain = new MysqlDataManagerMain();
            MysqlDataManager mysql = new MysqlDataManager();
            List<String> bannerIdList = new ArrayList<String>();
            
            //lay cac banner theo cpc trong ngay
            //String currentDate = TimeUtil.getCurrentTimeInString();//2012-07-24
            String currentDate = HandleDataTableDomainDate.handleDate();//2012-07-24
            //String currentDate = CONSTANT.Date;
            String[] arrTime = new String[3];
            arrTime = removeSpaces(currentDate).split("-");
            
            bannerIdList = mysqlmain.getValidBanner(currentDate);
            Map<String,String> mp=new HashMap<String, String>();
            
            //chon banner cpc va cpc plus
            mp = mysqlmain.getAllBannerHasDomain(currentDate);
            
            for(int j=0 ;j < 24 ;j++)
            {
                for(int t = 0;t < 4 ;t++)
                {
                    // end time
                    Calendar endCalendar = Calendar.getInstance();
                    endCalendar.set(Integer.valueOf(arrTime[0]), Integer.valueOf(arrTime[1])-1, Integer.valueOf(arrTime[2]), j, t*15, 00);
                    endCalendar.set(Calendar.MILLISECOND, 0);
                    endCalendar.set(Calendar.SECOND, 0);
                    long time = endCalendar.getTimeInMillis();
                    
                    List<FraudBannerTimestampDomain> fraudGuidInSecRangeResults = new FraudCountDomainPerBannerInTimestamp().countFraudGuidInSecSlice(bannerIdList, time);
                    Iterator it = fraudGuidInSecRangeResults.iterator();
                    //String insertDate = "2012-07-07";
                    while(it.hasNext())
                    {
                        FraudBannerTimestampDomain value = (FraudBannerTimestampDomain) it.next();
                        if(value.getListDomain().isEmpty())
                        {
                            continue;
                        } else
                        {
                            //domain cua theo banner tu log
                            domainList = value.getListDomain();
                            //domain cua banner treo
                            String strDomain = mp.get(value.getBannerId());
                            
                            if(strDomain != null)
                            {
                                arrDomain = strDomain.split(",");
                                
                                for(int i= 0 ; i < arrDomain.length ;i++)
                                {
                                    if(domainList.contains(arrDomain[i]))
                                    {
                                        domainList.remove(arrDomain[i]);
                                    }
                                }
                            }
                            
                            if (!domainList.isEmpty())
                            {
                                for(int i = 0;i < domainList.size();i++)
                                {
                                    String str = cassAct.getFraudClickDomain(value.getBannerId()+"_"+value.getTimeStamp()+"_"+domainList.get(i),ColumFamlyBannerTimestampDomain, currentDate);
                                    //check null
                                    if(str.length() > 1)
                                    {
                                        count++;
                                        String valInsert = str.substring(0, (str.length()-1));
                                        mysql.insertFraudClick(valInsert);
                                    }
                                }
                            }
                        }
                    }
                }
            }

       } catch (Exception ex)
        {
            System.out.println("exception sucess rule 4:"+ex.getMessage());
        }
        long last_time = System.currentTimeMillis();          
        Debug.println("so luong fraudclic theo domain:"+count);
        Debug.println("sucess rule 4");
        Debug.println("Thoi gian chay  :" +(last_time-first_time));
    }

    public static String removeSpaces(String s) {
      StringTokenizer st = new StringTokenizer(s," ",false);
      String t="";
      while (st.hasMoreElements()) t += st.nextElement();
      return t;
    }

    /*
     * Lay thoi gian tu 6h sang ngay hom truoc toi 5h59 sang ngay hom sau
     * Coi la 1 ngay
     */
    public String handleDate()
    {
        String retDate = "";//2012-07-24
        String date = TimeUtil.getCurrentTimeInStringForLog();//yyyy/MM/dd H:mm:ss

        String[] arrTime = new String[2];
        String[] firstArrTime = new String[3];
        String[] secondArrTime = new String[3];

        arrTime = date.split(" ");
        firstArrTime    = arrTime[1].split(":");
        secondArrTime   = arrTime[0].split("-");
        //init checkDate if trigger from 0h -> 6h
        if(checkFraudClickbyDomain == 0)
        {
            checkFraudClickbyDomain = TimeUtil.getCurrentTime();
        }

        if(Integer.valueOf(firstArrTime[0]) >= 6 && Integer.valueOf(firstArrTime[0]) <= 23)
        {
            checkFraudClickbyDomain = TimeUtil.getCurrentTime();
            retDate = secondArrTime[0]+"-"+secondArrTime[1]+"-"+secondArrTime[2];
        } else if (Integer.valueOf(firstArrTime[0]) >= 0 && Integer.valueOf(firstArrTime[0]) < 6 && TimeUtil.getCurrentTime() >= checkFraudClickbyDomain)
        {
            Debug.println(date + "_" + TimeUtil.getCurrentTime() + "_" + checkFraudClickbyDomain);
            int day = Integer.valueOf(secondArrTime[2]) - 1;
            retDate = secondArrTime[0]+"-"+secondArrTime[1]+"-"+String.valueOf(day);
        }
        return retDate;
    }
}
